package src.tree;

import java.util.ArrayDeque;

public class no404 {//左叶子之和

    public int sumOfLeftLeaves(TreeNode root) {
        if (root == null) return 0;
        int sum = 0;
        //采用后序遍历
        int left = sumOfLeftLeaves(root.left);
        int right = sumOfLeftLeaves(root.right);

        //判断左叶子的逻辑
        int cur = 0;
        if (root.left != null && root.left.left == null && root.left.right == null) {
            cur = root.left.val;//记录当前遍历到的左叶子值
        }
        sum += cur + left + right;
        return sum;

    }

    //迭代法
    public int sumOfLeftLeaves2(TreeNode root) {
        if (root == null) return 0;
        ArrayDeque<TreeNode> queue = new ArrayDeque<>();
        int sum = 0;
        queue.add(root);
        while (!queue.isEmpty()) {
            TreeNode node = queue.poll();
            if (node.left != null && node.left.left == null && node.left.right == null) {
                sum += node.left.val;
            }
            if (node.right != null) queue.add(node.right);
            if (node.left != null) queue.add(node.left);

        }
        return sum;

    }

}
